//
//  RankSecondLevelController.m
//  Kugou-OC
//
//  Created by BH on 16/6/15.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "RankSecondLevelController.h"
#import "GlobalDefine.h"
#import "UIImage+UIColor.h"
#import "UINavigationBar+Background.h"
#import "NetworkHelper.h"
#import "RecommendModel.h"
#import "ExpendCommonCell.h"
#import "BottomPlayView.h"
#import "MusicInfoModel.h"
#import "PlayHelper.h"
#import <MJRefresh/MJRefresh.h>
#import <SDAutoLayout/UIView+SDAutoLayout.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface RankSecondLevelHeaderView : UIView
{
    UIImageView *headerImg;
}

@property(nonatomic,copy)NSString *iconUrl;

@end

@implementation RankSecondLevelHeaderView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        headerImg = ALLOC(UIImageView);
        [self addSubview:headerImg];

        headerImg.sd_layout.leftEqualToView(self).topEqualToView(self).rightEqualToView(self).bottomEqualToView(self);
    }
    
    return self;
}

-(void)setIconUrl:(NSString *)iconUrl{
    _iconUrl = iconUrl;
    
    [headerImg sd_setImageWithURL:[NSURL URLWithString:iconUrl] placeholderImage:IMAGE(@"placeholder_rectangle")];
}

@end

@interface RankSecondLevelController ()<UITableViewDelegate,UITableViewDataSource>{
    RankSecondLevelHeaderView *headerView;
    
    NSInteger page;
    NSIndexPath *selectedIndexPath;//选中行
    NSInteger playIndex;//播放索引
}

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *singList;

@end

@implementation RankSecondLevelController

-(NSMutableArray *)singList{
    if (_singList == nil) {
        _singList = ALLOC(NSMutableArray);
    }
    
    return _singList;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[self getImageWithAlpha:1] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.barStyle=UIBarStyleDefault;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.shadowImage=[UIImage new];
    [self.navigationController.navigationBar setBackgroundImage:[self getImageWithAlpha:1] forBarMetrics:UIBarMetricsDefault];
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    [self scrollViewDidScroll:self.tableView];
    
    self.rightItems = @{@"img1":@"playview_share",@"img2":@"top_list"};
    page = 1;
    playIndex = -1;//处理row==0的情况
    
    [self.view addSubview:self.tableView];
    
    [self getData];
}

-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-90)];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        headerView = [[RankSecondLevelHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
        headerView.iconUrl = nil;
        _tableView.tableHeaderView = headerView;
        
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
        
    }
    
    return _tableView;
}

//footer 加载更多
-(void)loadMore{
    page++;
    [self getData];
}

-(void)getData{
    
    NSString *url = @"http://ioscdn.kugou.com/api/v3/rank/song";
    NSDictionary *param = @{@"rankid":self.rankModel.rankID,@"ranktype":@(self.rankModel.ranktype),@"page":@(page),@"pagesize":@(30),@"volid":@"",@"plat":@"2",@"version":@"8100"};
    
    UIView *paramView = nil;
    if (page==1) {
        paramView = self.view;
    }
    
    [[NetworkHelper shareNetwork] getDataWithUrl:url params:param view:paramView success:^(id response) {
        NSArray *info = response[@"data"][@"info"];
        NSMutableArray *tempArr = ALLOC(NSMutableArray);
        for (NSDictionary *dict in info) {
            RecommendModel *model = [[RecommendModel alloc] initWithSongDict:dict];
            
            MusicInfoModel *musicInfo = ALLOC(MusicInfoModel);
            musicInfo.music_source = kMusicSourceNetwork;
            NSArray *temp = [model.son_filename componentsSeparatedByString:@"-"];
            musicInfo.music_name = [[[temp lastObject] componentsSeparatedByString:@"."] firstObject];
            musicInfo.music_artist = [temp firstObject];
            musicInfo.music_extname = @"m4a";
            musicInfo.music_type = model.son_extname;
            musicInfo.music_hash = model.son_hash;
            [tempArr addObject:musicInfo];
        }
        
        [self.singList addObjectsFromArray:tempArr];
        
        if (tempArr.count == 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableview datasource & delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.singList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ExpendCommonCell *cell = [[ExpendCommonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
    MusicInfoModel *model = self.singList[indexPath.row];
    cell.titleLab.text = model.music_name;
    cell.subtitleLab.text = model.music_artist;
    [cell.rightBtn addTarget:self action:@selector(expendCell:) forControlEvents:UIControlEventTouchUpInside];
    cell.itemsDict = @{@"localmusic_soundquality":@"升级音质",@"localmusic_add":@"添加",@"localmusic_share":@"分享",@"localmusic_singinfo":@"歌曲信息",@"localmusic_delete":@"删除",@"localmusic_roaming":@"歌曲漫游",@"localmusic_k":@"K歌",@"localmusic_mv":@"MV"};
    
    if (indexPath == selectedIndexPath) {
        [cell addSubviewWithOpen:YES];
        
    }else{
        [cell addSubviewWithOpen:NO];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath == selectedIndexPath) {
        return 180;
    }
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    playIndex = indexPath.row;
    //判断缓存中是否存在当前文件
    MusicInfoModel *model = self.singList[indexPath.row];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *finalPath = [CACHE_DIRECTORY stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@.%@",model.music_artist,model.music_name,model.music_extname]];
    if ([fileManager fileExistsAtPath:finalPath]) {
        NSLog(@"有缓存");
        
        [self setUpPlayerWithModel:model];
        
    }else{
        NSLog(@"无缓存");
        //获取音乐下载地址
        [self getMusicUrl:[NSString stringWithFormat:@"%@-%@.%@",model.music_artist,model.music_name,model.music_extname]];
    }
}

/**
 *  音乐下载
 *
 *  @param path 文件名
 */
-(void)getMusicUrl:(NSString *)path{

    NSDictionary *params = @{@"hash":[self.singList[playIndex] music_hash],@"cmd":@"playInfo"};
    [[PlayHelper sharePlayHelper] getMusicUrlWithParam:params method:@"async" success:^(id JSON) {
        
        NSString *downloadUrl = JSON[@"url"];
        [[PlayHelper sharePlayHelper] downloadMusicWithUrl:downloadUrl method:@"async" param:nil filename:path success:^(id JSON) {
            [self setUpPlayerWithModel:self.singList[playIndex]];
        } failure:^(NSError *error) {
            
        }];
        
    } failure:^(NSError *error) {
        
    }];
}

-(void)setUpPlayerWithModel:(MusicInfoModel *)model{
    BottomPlayView *bpv = [BottomPlayView shareBottomView];
    bpv.musicList = self.singList;
    bpv.currentPlayIndex = playIndex;
    [bpv setupPlayerWithModel:model];
    
    __block BottomPlayView *bpvBlock = bpv;
    //播放下一首
    bpvBlock.NextSong = ^() {
        //判断缓存中是否存在当前文件
        playIndex++;
        MusicInfoModel *model = self.singList[playIndex];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *finalPath = [CACHE_DIRECTORY stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@.%@",model.music_artist,model.music_name,model.music_extname]];
        if ([fileManager fileExistsAtPath:finalPath]) {
            NSLog(@"有缓存");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [bpv setupPlayerWithModel:model];
            });
            
        }else{
            NSLog(@"无缓存");
            //获取音乐下载地址
            [self getMusicUrl:[NSString stringWithFormat:@"%@-%@.%@",model.music_artist,model.music_name,model.music_extname]];
        }
    };
}

//伸缩cell
-(void)expendCell:(id)sender{
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:((ExpendCommonCell*)[[sender superview]superview])];
    
    [self.tableView beginUpdates];
    if(selectedIndexPath==nil)
    {
        selectedIndexPath=indexPath;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else{
        BOOL hasSelectedOtherRow = ![selectedIndexPath isEqual:indexPath];
        
        NSIndexPath *temp=selectedIndexPath;
        selectedIndexPath=nil;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:temp] withRowAnimation:UITableViewRowAnimationAutomatic];
        if(hasSelectedOtherRow){
            selectedIndexPath=indexPath;
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
    [self.tableView endUpdates];
}

//scrollView的方法视图滑动时 实时调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    if (self.tableView == scrollView) {
//        CGFloat yOffset = self.tableView.contentOffset.y;
//        //下拉图片放大
//        if (yOffset < 0) {
//            headerView.frame = CGRectMake(0, yOffset, SCREEN_WIDTH, 150 + ABS(yOffset));
//        }
//        else {
//            headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 + ABS(yOffset));
//        }
//    }
    
    if(scrollView.contentOffset.y<0) {
        
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        
    }else{
        
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        
        CGFloat alpha=scrollView.contentOffset.y/90.0f>1.0f?1:scrollView.contentOffset.y/90.0f;
        
        [self.navigationController.navigationBar setBackgroundImage:[self getImageWithAlpha:alpha] forBarMetrics:UIBarMetricsDefault];
    }
}

#pragma handle image -mark
//根据颜色生成图片
-(UIImage *)getImageWithAlpha:(CGFloat)alpha{
    
    UIColor *color= COLOR(44, 120, 218, alpha);
    CGSize colorSize=CGSizeMake(1, 1);
    UIGraphicsBeginImageContext(colorSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
    
    UIImage *img=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return img;
}

@end
